package design_pattern.ProductConsumeMode;

import java.util.LinkedList;

/**
 * @Author: 蔡翔
 * @Date: 2019/11/14 15:48
 * @Version 1.0
 */
public class MessageQueue {
    private final LinkedList<Message> queue;
    private final static int DEFAULT_MAX_LIMIT = 100;
    private final int limit;

    public MessageQueue(){
        //this.queue = new LinkedList<Message>();
        this(DEFAULT_MAX_LIMIT);
    }
    public MessageQueue(final int limit){
        this.limit = limit;
        this.queue = new LinkedList<>();
    }

    public void put(final Message message) throws InterruptedException {
        synchronized (queue){
            while (queue.size()>limit){
                queue.wait();
            }
            queue.addLast(message);
            queue.notifyAll();
        }
    }

    public Message take() throws InterruptedException {
        synchronized (queue){
            while (queue.isEmpty()){
                queue.wait();
            }
            Message message = queue.removeFirst();
            //可能会有因 queue满了 某些线程被阻塞住，所以这里拿出来一条要去唤醒那些阻塞住的。
            queue.notifyAll();
            return message;
        }
    }

    public int getMaxLimit(){
        return this.limit;
    }

    public int getMessageSize(){
        synchronized (queue){
            return queue.size();
        }
    }
}